package com.itheima.app.manager;

import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.service.db.UserInfoService;
import com.itheima.util.TestSoulUtil;
import com.itheima.vo.OptionsVo;
import com.itheima.vo.QuestionsVo;
import com.itheima.vo.ReportedVo;
import com.itheima.vo.SurveyVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author RMY
 * @Date 2021/11/12 9:31
 * @Version 1.0
 */
@Component
public class TestSoulManager {
    @DubboReference
    private TestSoulService testSoulService;
    @DubboReference
    private UserInfoService userInfoService;
    //app端查询所有题库
    public ResponseEntity findAllSurvey() {
        //查询用户id
        Long userId = UserHolder.get().getId();
        //每个用户插入三条初始锁记录(先判断是否有，有就不插)
        List<QuestionUserLock> questionUserLockList = testSoulService.findQuestionUserLockByUserId(userId);
        if (questionUserLockList.size()==0){
            QuestionUserLock questionUserLock1 = new QuestionUserLock();
            QuestionUserLock questionUserLock2 = new QuestionUserLock();
            QuestionUserLock questionUserLock3 = new QuestionUserLock();
            questionUserLock1.setUserId(userId);
            questionUserLock1.setSurveyId(1L);
            questionUserLock1.setIsLock(0);
            questionUserLock2.setUserId(userId);
            questionUserLock2.setSurveyId(2L);
            questionUserLock2.setIsLock(1);
            questionUserLock3.setUserId(userId);
            questionUserLock3.setSurveyId(3L);
            questionUserLock3.setIsLock(1);
            testSoulService.saveQuestionUserLock(questionUserLock1);
            testSoulService.saveQuestionUserLock(questionUserLock2);
            testSoulService.saveQuestionUserLock(questionUserLock3);
        }
        //1.根据用户id，查询QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        List<QuestionUserLock> lockList = testSoulService.findQuestionUserLockByUserId(userId);
        //初始化SurveyVoList,QuestionsVoList
        List<SurveyVo> surveyVoList = new ArrayList<>();
        //遍历封装
        for (QuestionUserLock questionUserLock : lockList) {
            SurveyVo surveyVo = new SurveyVo();
            surveyVo.setId(questionUserLock.getSurveyId().toString());
            surveyVo.setIsLock(questionUserLock.getIsLock());
            surveyVoList.add(surveyVo);
        }

        //2.取出封装的问卷id集合,放入surveyIdList
        List<Long> surveyIdList = new ArrayList<>();
        for (QuestionUserLock questionUserLock : lockList) {
            surveyIdList.add(questionUserLock.getSurveyId());
            //System.out.println(questionUserLock.getSurveyId());
        }
        //查询结果集合
        List<Survey> surveyList = testSoulService.findSurveyBySurveyIdList(surveyIdList);
        //遍历集合并封装VO
        List<String> reportedIdList = new ArrayList<>();
        for (Survey survey : surveyList) {
            //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
            for (SurveyVo surveyVo : surveyVoList) {
                if (survey.getId().toString().equals(surveyVo.getId())){
                    surveyVo.setLevel(survey.getLevel());
                    surveyVo.setName(survey.getName());
                    surveyVo.setCover(survey.getCover());
                    surveyVo.setStar(survey.getStar());
                    //判断该人是否已做题
                    Reported reported = testSoulService.findReportedByUserId(UserHolder.get().getId());
                    if (reported != null){
                        //并且保证是最后一套题
                        if (reported.getSurveyId() == 3){
                            surveyVo.setReportId(reported.getId().toString());
                        }
                    }else {
                        surveyVo.setReportId(null);
                    }
                }
//
            }

        }
        //3.接着把QuestionVO添加到SurveyVo
        for (SurveyVo surveyVo : surveyVoList) {
            //System.out.println(surveyVo.getName());
            List<Questions> questionsList = testSoulService.findQuestionsBySurveyId(Long.parseLong(surveyVo.getId()));
            //System.out.println(surveyIdList);
                List<QuestionsVo> questionVoList = new ArrayList<>();
                //遍历封装questionsVo
                for (Questions questions : questionsList) {
                    //封装
                    QuestionsVo questionsVo = new QuestionsVo();
                    questionsVo.setId(questions.getId().toString());
                    questionsVo.setQuestion(questions.getQuestion());
                    questionVoList.add(questionsVo);
                    //封装optionVo
                    List<Options> optionsList = testSoulService.findOptionsByQuestionsId(questions.getId());
                    List<OptionsVo> optionsVoList = new ArrayList<>();
                    for (Options options : optionsList) {
                        OptionsVo optionsVo = new OptionsVo();
                        optionsVo.setOption(options.getOpt());
                        optionsVo.setId(options.getId().toString());
                        //添加到集合
                        optionsVoList.add(optionsVo);
                    }
                    questionsVo.setOptions(optionsVoList);
                }
                surveyVo.setQuestions(questionVoList);
            System.out.println(surveyVo);
        }

        //返回结果
        return ResponseEntity.ok(surveyVoList);
    }


    //接受答题的题号和选择号,并结算结果，把reportedId返回
    public ResponseEntity computeAndReturnReportedId(List<Answers> answers) {
        //初始化总分
        Integer sum = 0;
        //初始化问题id
        Long questionId = 0L;
        //用户Id
        Long userId = UserHolder.get().getId();
//        //每个用户先查一下是否有答题记录
//        List<Reported> reportedList = testSoulService.findReprotedByUserId(userId);
//        //有的话，给返回题号
//        if ()
        //初始化Reported
        Reported reported = new Reported();
        //对结果判分
        for (Answers answer : answers) {
            String optionId = answer.getOptionId();
            //题号
            questionId = Long.parseLong(answer.getQuestionId());
            //如果level为
            //根据选项Id找到对应的分数相加得出总分
            Options options = testSoulService.findByOptionId(Long.parseLong(optionId));
            Integer score = options.getScore();
            sum = sum+score;
        }
        //根据题目Id查询问卷id
        Questions questions = testSoulService.findQuestionsByQuestionsId(questionId);
        Long surveyId = questions.getSurveyId();

        if (surveyId <= 2){
            //难度为初级或中级时，更新question_user_lock表
            QuestionUserLock questionUserLock = testSoulService.findQuestionUserLockByUserIdAndSurveyId(userId,surveyId);
            if (questionUserLock.getIsLock() == 1){
                //如果下一级被锁，解锁
                questionUserLock.setIsLock(0);
                //更新
                testSoulService.updateQuestionUserLock(questionUserLock);
            }
        }
        reported.setUserId(UserHolder.get().getId());
        //得出总分，将改分数细分（分类）,并放入reported表中
        if (sum>=10&&sum<=20){
            //猫头鹰
           reported.setResult(sum);
           reported.setSurveyId(surveyId);
           reported.setConclusion(TestSoulUtil.maoTouYing);
           reported.setCover(TestSoulUtil.maoTouYingPic);
        }else if (sum>20&&sum<=30){
            //狮子
            reported.setResult(sum);
            reported.setSurveyId(surveyId);
            reported.setConclusion(TestSoulUtil.shiZi);
            reported.setCover(TestSoulUtil.shiZiPic);
        }else {
            //狐狸
            reported.setResult(sum);
            reported.setSurveyId(surveyId);
            reported.setConclusion(TestSoulUtil.huLi);
            reported.setCover(TestSoulUtil.huLiPic);
        }
        //调用rpc，插入该记录
        //先查询是否有该记录，有的话就更新
        Reported searchReported = testSoulService.findByReportedId(reported.getId());
        if (searchReported!=null){
            //不为空就更新
            testSoulService.updateReported(reported);
        }
        //为空就插入
        Long reportedId = testSoulService.saveReported(reported);
        //返回报告id
        return ResponseEntity.ok(reportedId.toString());
    }

    //查看自己的结果
    public ResponseEntity findReportedById(String reportedId) {
        //调用rpc
        Reported reported = testSoulService.findByReportedId(Long.parseLong(reportedId));
        //根据他的分数判断，合理的给出维度,并封装VO,注意！！返回的vo中包含相似度较高的用户
        ReportedVo reportedVo = new ReportedVo();
        Integer result = reported.getResult();
        //初始化维度
        List<Dimensions> dimensionsList = new ArrayList<>();
        if (result>=10&&result<=20){
            //猫头鹰
            reportedVo.setConclusion(reported.getConclusion());
            reportedVo.setCover(reported.getCover());
            //初始化dimensions
            Dimensions dimensions1 = new Dimensions();
            dimensions1.setKey(TestSoulUtil.LI_XING);
            dimensions1.setValue(TestSoulUtil.SEVENTY);
            Dimensions dimensions2 = new Dimensions();
            dimensions2.setValue(TestSoulUtil.CHOU_XIANG);
            dimensions2.setKey(TestSoulUtil.EIGHTY);
            Dimensions dimensions3 = new Dimensions();
            dimensions3.setKey(TestSoulUtil.PAN_DUAN);
            dimensions3.setValue(TestSoulUtil.NINETY);
            Dimensions dimensions4 = new Dimensions();
            dimensions4.setKey(TestSoulUtil.WAI_XIANG);
            dimensions4.setValue(TestSoulUtil.SIXTY);
            dimensionsList.add(dimensions1);
            dimensionsList.add(dimensions2);
            dimensionsList.add(dimensions3);
            dimensionsList.add(dimensions4);
            reportedVo.setDimensions(dimensionsList);
            //查找分数相似度用户的id
            List<Long> userIdList = testSoulService.findSimilarYou(reported.getSurveyId(),result);
            //初始化集合
            List<SimilarYou> similarYouList = new ArrayList<>();
            //遍历用户Id，查询用户详细信息
            for (Long userId : userIdList) {
                if (userId != UserHolder.get().getId()) {
                    UserInfo userInfo = userInfoService.findUserInfoById(userId);
                    //初始化similarYou
                    SimilarYou similarYou = new SimilarYou();
                    similarYou.setId(userId.intValue());
                    similarYou.setAvatar(userInfo.getAvatar());
                    similarYouList.add(similarYou);
                }
            }
            //封装similarYouList
            reportedVo.setSimilarYou(similarYouList);
            //返回VO
            return ResponseEntity.ok(reportedVo);
        }else if (result>20&&result<=30){
            //狮子
            reportedVo.setConclusion(reported.getConclusion());
            reportedVo.setCover(reported.getCover());
            //初始化dimensions
            Dimensions dimensions1 = new Dimensions();
            dimensions1.setKey(TestSoulUtil.LI_XING);
            dimensions1.setValue(TestSoulUtil.SEVENTY);
            Dimensions dimensions2 = new Dimensions();
            dimensions2.setValue(TestSoulUtil.CHOU_XIANG);
            dimensions2.setKey(TestSoulUtil.EIGHTY);
            Dimensions dimensions3 = new Dimensions();
            dimensions3.setKey(TestSoulUtil.PAN_DUAN);
            dimensions3.setValue(TestSoulUtil.NINETY);
            Dimensions dimensions4 = new Dimensions();
            dimensions4.setKey(TestSoulUtil.WAI_XIANG);
            dimensions4.setValue(TestSoulUtil.SIXTY);
            dimensionsList.add(dimensions1);
            dimensionsList.add(dimensions2);
            dimensionsList.add(dimensions3);
            dimensionsList.add(dimensions4);
            reportedVo.setDimensions(dimensionsList);
            //查找分数相似度用户的id
            List<Long> userIdList = testSoulService.findSimilarYou(reported.getSurveyId(),result);
            //初始化集合
            List<SimilarYou> similarYouList = new ArrayList<>();
            //遍历用户Id，查询用户详细信息
            for (Long userId : userIdList) {
                if (userId != UserHolder.get().getId()){
                    //排除自己
                    UserInfo userInfo = userInfoService.findUserInfoById(userId);
                    //初始化similarYou
                    SimilarYou similarYou = new SimilarYou();
                    similarYou.setId(userId.intValue());
                    similarYou.setAvatar(userInfo.getAvatar());
                    similarYouList.add(similarYou);
                }

            }
            //封装similarYouList
            reportedVo.setSimilarYou(similarYouList);
            //返回VO
            return ResponseEntity.ok(reportedVo);
        }else {
            //狐狸
            reportedVo.setConclusion(reported.getConclusion());
            reportedVo.setCover(reported.getCover());
            //初始化dimensions
            Dimensions dimensions1 = new Dimensions();
            dimensions1.setKey(TestSoulUtil.LI_XING);
            dimensions1.setValue(TestSoulUtil.SEVENTY);
            Dimensions dimensions2 = new Dimensions();
            dimensions2.setValue(TestSoulUtil.CHOU_XIANG);
            dimensions2.setKey(TestSoulUtil.EIGHTY);
            Dimensions dimensions3 = new Dimensions();
            dimensions3.setKey(TestSoulUtil.PAN_DUAN);
            dimensions3.setValue(TestSoulUtil.NINETY);
            Dimensions dimensions4 = new Dimensions();
            dimensions4.setKey(TestSoulUtil.WAI_XIANG);
            dimensions4.setValue(TestSoulUtil.SIXTY);
            dimensionsList.add(dimensions1);
            dimensionsList.add(dimensions2);
            dimensionsList.add(dimensions3);
            dimensionsList.add(dimensions4);
            reportedVo.setDimensions(dimensionsList);
            //查找分数相似度用户的id
            List<Long> userIdList = testSoulService.findSimilarYou(reported.getSurveyId(),result);
            //初始化集合
            List<SimilarYou> similarYouList = new ArrayList<>();
            //遍历用户Id，查询用户详细信息
            for (Long userId : userIdList) {
                //排除自己
                if (userId != UserHolder.get().getId()){
                    UserInfo userInfo = userInfoService.findUserInfoById(userId);
                    //初始化similarYou
                    SimilarYou similarYou = new SimilarYou();
                    similarYou.setId(userId.intValue());
                    similarYou.setAvatar(userInfo.getAvatar());
                    similarYouList.add(similarYou);
                }
            }
            //封装similarYouList
            reportedVo.setSimilarYou(similarYouList);
            //返回VO
            return ResponseEntity.ok(reportedVo);
        }

    }
}
